<?php

namespace App\Http\Controllers;

use App\Models\BorrowBook;
use Carbon\Carbon;
use Illuminate\Http\Request;

class UserController extends Controller
{


    public function index(Request $request)
    {
        $type = $request->input('type', '');
        $data = null;
        $auditCount = 0;
        if ($type == 'records') {
            // 刷新逾期记录
            $dataList = BorrowBook::where('user_id', auth()->user()->id)->where('status', BorrowBook::STATUS_BORROW)->get();
            foreach ($dataList as $item) {
                $inDay = Carbon::now()->diffInDays($item->borrow_date);
                // 刷新借阅天数
                if ($inDay < auth()->user()->level->limit_day) {
                    $item->update(
                        ['illegal' => '借阅 ' . $inDay . ' 天']
                    );
                } else {
                    $item->update(
                        ['illegal' => '已逾期 ' . $inDay - auth()->user()->level->limit_day . ' 天']
                    );
                }
            }


            $data = BorrowBook::with(['user', 'book'])->where('user_id', auth()->id())->orderBy('created_at', 'desc')->paginate(10);
            $auditCount = BorrowBook::where('user_id', auth()->id())->where('status', BorrowBook::STATUS_APPROVAL)->count();
        }

        if ($type == 'audit') {
            $data = BorrowBook::with(['user', 'book'])->where('status', BorrowBook::STATUS_APPROVAL)->orderBy('created_at', 'desc')->paginate(10);
            $auditCount = BorrowBook::where('status', BorrowBook::STATUS_APPROVAL)->count();
        }

        return view('user.user', compact('data', 'auditCount'));
    }

    public function updateInfo(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'nickname' => 'required',
        ], [
            'name.required' => '用户名不能为空',
            'nickname.required' => '昵称不能为空',
        ]);

        if ($request->password != '') {
            $this->validate($request, [
                'password' => 'required',
                'password_confirmation' => 'required|same:password',
            ], [
                'password.required' => '密码不能为空',
                'password_confirmation.required' => '确认密码不能为空',
                'password_confirmation.same' => '两次密码不一致',
            ]);
        }

        // 更新用户信息
        $user = auth()->user();
        $user->name = $request->name;
        $user->nickname = $request->nickname;
        if ($request->password != '') {
            $user->password = bcrypt($request->password);
        }
        $user->save();
        return back()->with('success', '修改成功');
    }

}
